//
//  AppDelegate.m
//  NavZe
//
//  Created by ZengYuan on 15/7/31.
//  Copyright (c) 2015年 ZengYuan. All rights reserved.
//

#import "AppDelegate.h"
#import "UserUnit.h"
#import "LoginViewController.h"
#import "HomeViewController.h"
#import "MeViewController.h"
#import "ZYNavigationController.h"
#import <SMS_SDK/SMSSDK.h>
#import "SupportViewController.h"
#import "MallViewController.h"
#import "APService.h"

#import <ShareSDK/ShareSDK.h>
#import "WXApi.h"

#import <TencentOpenAPI/QQApi.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import <QZoneConnection/ISSQZoneApp.h>
#import "UserLogin.h"

#define KOTHERPLACE_TITLE @"下线通知"
#define KOTHERPLACE_CONTENT @"您的账号已经在别的设备上登录或者当前登录已过期"

@interface AppDelegate ()
{
    NSString* remotePushId;
}
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    
    [self initShareSDK];
    
    //sms
    [SMSSDK registerApp:@"f82a7ba7e707" withSecret:@"3bb4cd0e7d31d595beed0c251014b767"];
    
    [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                   UIRemoteNotificationTypeSound |
                                                   UIRemoteNotificationTypeAlert)
                                       categories:nil];
    [APService setupWithOption:launchOptions];
    
    
    if (![[NSUserDefaults standardUserDefaults] objectForKey:KFIRSTRUN]) {
        [[NSUserDefaults standardUserDefaults] setObject:@"KFIRSTRUN" forKey:KFIRSTRUN];
        [[NSUserDefaults standardUserDefaults] setObject:@"KSWITCH_LANDSCAPE" forKey:KSWITCH_LANDSCAPE];
        [[NSUserDefaults standardUserDefaults] setObject:@"KSWITCH_NOWIFIALERT" forKey:KSWITCH_NOWIFIALERT];
    }
    
    
    [self addRootViewController];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(accountHasLoginedInOtherPlace:) name:KANOTHERLOGIN_NOTI object:nil];
    return YES;
}

#pragma mark - OnlineEngineDelegate
-(void)accountHasLoginedInOtherPlace:(NSNotification *)nf{
    NSLog(@"accountHasLoginedInOtherPlace");
    
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:KOTHERPLACE_TITLE message:KOTHERPLACE_CONTENT delegate:self cancelButtonTitle:nil otherButtonTitles: @"退出",@"重新登录", nil];
    alert.tag=500;
    [alert show];
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 500) {
        if(buttonIndex==0){
            [self returnLoginContrller];
        }else{
            [self loginAsync];
        }
    }
}

-(void)loginAsync{
    UserUnit *user = [UserUnit getActiveUser];
    if(user.userName && user.userPasswd){
        
        [UserLogin loginBy:user.userName andPwd:user.userPasswd success:^{
        } failure:^(NSString *error) {
            [self returnLoginContrller];
        }];
    }
}

- (void)initShareSDK{
    [ShareSDK registerApp:@"f3d9f6079262"];
    
    [ShareSDK connectWeChatWithAppId:@"wx4ef3d4cade6d1221"
                           appSecret:@"b61eafc2325f6eff436a87cbacb4bbf6"
                           wechatCls:[WXApi class]];
    
    //导入QQ互联和QQ好友分享需要的外部库类型，如果不需要QQ空间SSO和QQ好友分享可以不调用此方法
    [ShareSDK importQQClass:[QQApiInterface class] tencentOAuthCls:[TencentOAuth class]];
}


-(void)addRootViewController{
    
    CATransition *animation = [CATransition animation];
    animation.duration = 0.5;
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
    animation.type = @"pageFade";
    animation.subtype = kCATransitionFade;
    [self.window.layer addAnimation:animation forKey:@"animation"];
    
    if ([UserUnit getActiveUser]) {
        
        [self initTabController:YES];
        self.window.rootViewController = self.tabController;
        
    }else{
        remotePushId = nil;
        
        UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        LoginViewController *evc = [board instantiateViewControllerWithIdentifier:@"loginvc"];
        
        UINavigationController*nav =[[UINavigationController alloc]initWithRootViewController:evc];
        self.window.rootViewController = nav;
        
    }
    
}

-(void)returnLoginContrller{
    
    //删除用户数据
    [UserUnit removeActiveUser];
    //返回登陆
    UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    LoginViewController *evc = [board instantiateViewControllerWithIdentifier:@"loginvc"];
    
    UINavigationController*nav =[[UINavigationController alloc]initWithRootViewController:evc];
    self.window.rootViewController = nav;
    
}


-(void)initTabController:(BOOL)needLogin{
    self.tabController = [[AWTabBarController alloc]init];
    
    HomeViewController *homevc = [[HomeViewController alloc]init];
    
    ZYNavigationController *navHome = [[ZYNavigationController alloc] initWithRootViewController:homevc];
    homevc.needLogin=needLogin;
    
    SupportViewController *msg = [[SupportViewController alloc] init];
    UINavigationController *navMsg = [[UINavigationController alloc] initWithRootViewController:msg];
    //
    //    MallViewController *mall = [[MallViewController alloc] init];
    //    UINavigationController *navMall = [[UINavigationController alloc] initWithRootViewController:mall];
    
    MeViewController *me = [[MeViewController alloc] init];
    UINavigationController *navme = [[UINavigationController alloc] initWithRootViewController:me];
    
    self.tabController.viewControllers = [NSArray arrayWithObjects:navHome,navMsg,navme, nil];
    [self.tabController setItems];
    
}

-(void)setTabAfterLogin{
    [self initTabController:NO];
    
    CATransition *animation = [CATransition animation];
    animation.duration = 0.5;
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
    animation.type = @"pageFade";
    animation.subtype = kCATransitionFade;
    [self.window.layer addAnimation:animation forKey:@"animation"];
    
    self.window.rootViewController = self.tabController;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    NSLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    [APService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}


#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
- (void)application:(UIApplication *)application
didRegisterUserNotificationSettings:
(UIUserNotificationSettings *)notificationSettings {
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [APService handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
    [APService handleRemoteNotification:userInfo];
    
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
    [APService showLocalNotificationAtFront:notification identifierKey:nil];
}


// Called when your app has been activated by the user selecting an action from
// a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forLocalNotification:(UILocalNotification *)notification
  completionHandler:(void (^)())completionHandler {
}

// Called when your app has been activated by the user selecting an action from
// a remote notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forRemoteNotification:(NSDictionary *)userInfo
  completionHandler:(void (^)())completionHandler {
}
#endif

@end
